/*
 * =====================================================================================
 *
 *       Filename:  test.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2019年09月06日 13时09分12秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *   Organization:  
 *
 * =====================================================================================
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <errno.h>

int main(int argc, char **argv)
{
    /* 初始化一个二值信号量 */
    if(argc != 2) {
        return printf("%s sem_path\n", argv[0]);
    }
    int ret = 0;
    sem_t *psem = sem_open(argv[1], O_RDWR | O_CREAT, 0666, 1);
    if(NULL == psem) {
        printf("sem_open(%s): %s\n", argv[1], strerror(errno));
        return -1;
    }
    
    int value = 0;
    sem_getvalue(psem, &value);
    printf("before wait value=%d\n", value);
    ret = sem_wait(psem);
    sem_getvalue(psem, &value);
    printf("after wait value=%d\n", value);
    if(ret < 0) {
        int err = errno;
        perror("sem_wait()");
        if(err == EINTR) {
            ;
        }
        else {
            goto this_exit;
        }
    }

    printf("pid=%d, Already sem_wait, Now Sleep For 5 Seconds\n", getpid());
    sleep(5);

    sem_getvalue(psem, &value);
    printf("before post value=%d\n", value);
    /* No Need to check return value */
    sem_post(psem);
    sem_getvalue(psem, &value);
    printf("after post value=%d\n", value);

this_exit:
    sem_close(psem);
    return 0;

}


